<template>
  <div>
    <el-upload action drag :auto-upload="false" :show-file-list="false" :on-change="handleUpload" accept=".tar.gz">
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">PNC文件(<em>tar.gz</em>)拖到此处，或点击上传</div>
      <div class="el-upload__tip" slot="tip">仅支持上传<em>tar.gz</em>格式的文件</div>
    </el-upload>

    <!-- 进度显示 -->
    <div class="progress-box" v-if="upload">
      <span>上传进度：{{ percent.toFixed() }}%</span>
    </div>
  </div>
</template>
<script>
import SparkMD5 from "spark-md5"
import axios from "axios"
import { uploadPnc , mergeUploadPnc} from '@/api/pnc'
  export default {
    name: 'UploadPnc',
    data(){
      return {
        percent: 0,
        upload: false,
        percentCount: 0
      }
    },
    methods:{
      async handleUpload(file) {
        const isTar = file.raw.type === "application/gzip"
        if (!file) return
        if(!isTar){
          this.$message.warning('请上传tar.gz格式的文件')
          return
        }
        this.upload = true
        this.percent = 0
        const fileObj = file.raw
        let buffer
        try {
          buffer = await this.fileToBuffer(fileObj)
        } catch (e) {
          console.log(e)
        }
        const chunkSize = 3145728, // 3M 3*1024*1024
          chunkList = [],
          chunkListLength = Math.ceil(fileObj.size / chunkSize)
          
        const spark = new SparkMD5.ArrayBuffer()
        spark.append(buffer)
        const hash = spark.end() // md5编码值（一个文件的标识）

        let curChunk = 0
        for (let i = 0; i < chunkListLength; i++) {
          const item = {
            chunk: fileObj.slice(curChunk, curChunk + chunkSize),
            fileName: `${fileObj.name}##${hash}##${i}`
          }
          curChunk += chunkSize
          chunkList.push(item)
        }
        this.chunkList = chunkList
        this.hash = hash
        this.sendRequest()
      },

      sendRequest() {
        const requestList = []
        this.chunkList.forEach((item, index) => {
          const fn = () => {
            const formData = new FormData()
            formData.append('chunk', item.chunk)
            formData.append('filename', item.fileName)
            return uploadPnc(formData).then(res => {
              if (res.code === 0) {
                if (this.percentCount === 0) {
                  this.percentCount = 100 / this.chunkList.length
                }
                this.percent += this.percentCount
                if(this.percent >100){
                  this.percent = 100
                }
                this.chunkList.splice(index, 1)
              }
            })
          }
          requestList.push(fn)
        })
        
        let i = 0
        const complete = () => {
          mergeUploadPnc({ hash: this.hash }).then(res => {
            if (res.code === 0) {
              this.$message.success('算法版本上传成功')
              setTimeout(()=>{
                this.upload = false
                this.$emit('refresh')
              },5000)
            }
          })
        }
        const send = async () => {
          if (!this.upload) return
          if (i >= requestList.length) {
            complete()
            return
          } 
          await requestList[i]()
          i++
          send()
        }
        send()
      },
      
      fileToBuffer(file) {
        return new Promise((resolve, reject) => {
          const fr = new FileReader()
          fr.onload = e => {
            resolve(e.target.result)
          }
          fr.readAsArrayBuffer(file)
          fr.onerror = () => {
            reject(new Error('转换文件格式发生错误'))
          }
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
::v-deep .el-upload{
  width: 100%;
}
  ::v-deep .el-upload-dragger{
    background-color: transparent !important;
    height: 150px; 
    width:100%;
    .el-icon-upload{
      margin: 30px 0 16px;
    }
  }
  .progress-box {
  box-sizing: border-box;
  // width: 360px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
  padding: 6px 10px;
  background-color: #ecf5ff;
  font-size: 14px;
  border-radius: 4px;
}
</style>
